from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from .models import User
from acdmpage.models import academy_page,paper,project,award,service,record
import hashlib
# Create your views here.

def reg_view(request):
    # 注册
    # Get返回页面
    #post提交
    #用户名是主键，必须保持唯一性
    #两次密码必须相同 密码加密操作
    #注册免登录 即session或cookie
    if request.method=='GET':
        return render(request,'user/register.html')

    elif request.method=='POST':
        # 用户名唯一性检查
        #密码安全性提示
        username=request.POST['username']
        mail_address = request.POST['mailaddr']
        pwd1 = request.POST['pwd1']
        pwd2 = request.POST['pwd2']
        # 密码必须一致
        if pwd1!=pwd2:
            return HttpResponse("两次密码输入不一致")
        # 哈希算法对密码加密
        obj_hash=hashlib.md5()
        obj_hash.update(pwd1.encode())
        pwd=obj_hash.hexdigest()
        #查询该用户名是否存在 检查用户名即主键唯一性
        not_availiable=User.objects.filter(username=username)
        if not_availiable:
            return HttpResponse("用户名已存在")
        try:
            User.objects.create(username=username, mail_address=mail_address, password=pwd)
            academy_page.objects.create(user_id=username)

        except Exception as e:
            # 并发写入可能报错
            print("---create user failed %s"%(e))
            return HttpResponse("用户名注册失败")
        # session免登录
        request.session['username']=username
        request.session['uid']=pwd[0:5]

        return HttpResponseRedirect("/index")


def login_view(request):
    if request.method=='GET':
        username = request.session.get('username')
        uid = request.session.get('uid')
        if not username:
            username = request.COOKIES.get('username')
            uid = request.COOKIES.get('uid')
            print("1", username)
            if username:
                request.session['username'] = username
                request.session['uid'] = uid

        try:
            user = User.objects.get(username=username)
            pwd = user.password
            if uid == pwd[0:5]:
                return HttpResponse("已登录 跳转首页")
        except Exception as e:
            print("没有找到cookie或session")
            return render(request,'user/login.html')
        return render(request,'user/login.html')

    elif request.method=='POST':
        username=request.POST['username']
        pwd = request.POST['pwd']
        try:
            user=User.objects.get(username=username)
        except Exception as e:
            print("---login failed %s"%(e))
            return HttpResponse("用户名或密码错误")
        obj_hash=hashlib.md5()
        obj_hash.update(pwd.encode())
        pwd=obj_hash.hexdigest()
        password=user.password
        if password!=pwd:
            return HttpResponse("用户名或密码错误")
        request.session['username']=username
        request.session['uid']=pwd[0:5]
        resp=HttpResponseRedirect("/index")
        if 'remember' in request.POST:
            resp.set_cookie('username',username,3600*24*3)
            resp.set_cookie('uid',pwd[0:5])
        return resp


def exit_view(request):
    response=HttpResponseRedirect('/index')
    user=request.session.get('username')
    try:
        if not user:
            user=request.COOKIES.get('username')
            if user:
                response.delete_cookie('username')
                response.delete_cookie('uid')
        else:
            request.session.flush()
            response.delete_cookie('username')
            response.delete_cookie('uid')
    except Exception as e:
        print("error occured when exit_view %s"%(e))
        return response


    return response
